package com.smartwebx.fr.service.ckeditor;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Objects;
import com.google.common.io.Resources;
import com.smartwebx.fr.bean.ChartImgPath;
import com.smartwebx.fr.bean.mysql.PageChart;
import com.smartwebx.fr.dao.mysql.PageChartMapper;
import com.smartwebx.fr.util.ChartOptionCache;
import com.smartwebx.fr.util.PathUtil;

@Service
@Transactional
public class SmartChartService {
	@Autowired
	private PageChartMapper pageChartDao;

	public String getCreateChartImage(StringBuffer requestUrlSB, Integer pageId, String chartId, String chartOption)
			throws IOException {
		int imgType;
		if ("empty_data".equals(chartOption)) {
			imgType = 1;
		} else if ("config_error".equals(chartOption)) {
			imgType = 2;
		} else if ("req_error".equals(chartOption)) {
			imgType = 3;
		} else {
			ChartOptionCache.putIdAndOpiton(chartId, chartOption);
			imgType = 0;
		}

		ChartImgPath chartImgPath = PathUtil.getChartImgPathInfo(requestUrlSB.toString(), pageId, chartId);
		// String chartImagePath = chartImgPath.getImgBaseUrl();
		final String fullImgPath = chartImgPath.getFullImgPath();
		if (imgType == 0) {
			boolean status = buildChartImageByPhantomJs(chartImgPath.getChartReqOptionUrl(), fullImgPath);
			if (status) {
				// chartImagePath = chartImagePath + pageId + "/" + chartId
				// + ".png";

				// 延迟1S后将路径下的图片删除
				new Thread() {
					@Override
					public void run() {
						try {
							Thread.sleep(1000 * 60);
							File del = new File(fullImgPath);
							del.delete();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}.start();
			}
			// else {
			// chartImagePath = chartImagePath + "empty_data.png";
			// }
		}
		// else if (imgType == 1) {
		// chartImagePath = chartImagePath + "empty_data.png";
		// } else if (imgType == 2) {
		// chartImagePath = chartImagePath + "config_error.png";
		// } else if (imgType == 3) {
		// chartImagePath = chartImagePath + "req_error.png";
		// } else {
		// chartImagePath = chartImagePath + "empty_data.png";
		// }

		return fullImgPath;
	}

	private boolean buildChartImageByPhantomJs(String url, String fullFilePath) throws IOException {
		String phantomjsPath = Resources.getResource("show_config/phantomjs_chart/phantomjs.exe").getFile();
		phantomjsPath = phantomjsPath.substring(1);

		String scriptJs = Resources.getResource("show_config/phantomjs_chart/echarts-convert.js").getFile();
		scriptJs = scriptJs.substring(1);

		Runtime rt = Runtime.getRuntime();
		Process p = null;
		String commond = "%s %s -url %s -outfile %s";
		commond = String.format(commond, phantomjsPath, scriptJs, url, fullFilePath);
		try {
			p = rt.exec(commond);
		} catch (Exception e) {
			e.printStackTrace();
		}
		InputStream is = p.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuffer sbf = new StringBuffer();
		String tmp = "";
		while ((tmp = br.readLine()) != null) {
			sbf.append(tmp);
		}
		return Objects.equal(sbf.toString(), "success");
	}

	public PageChart getPageChartById(String chartId) {
		return pageChartDao.selectByPrimaryKey(chartId);
	}

	public void saveOrUpdate(PageChart pageChart) {
		String chartId = pageChart.getId();
		// 0 save;1 update
		int state = 0;
		if (chartId != null) {
			PageChart dbChart = pageChartDao.selectByPrimaryKey(chartId);
			if (dbChart != null) {
				state = 1;
			}
		}
		if (state == 0) {
			pageChartDao.insertSelective(pageChart);
		} else {
			pageChartDao.updateByPrimaryKeySelective(pageChart);
		}
	}
}
